package com.miplus.ccrm.workflow.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.miplus.ccrm.common.CmdResVo;
import com.miplus.ccrm.common.EnumRCode;
import com.miplus.ccrm.common.JPubUtils;
import com.miplus.ccrm.common.ServiceException;
import com.miplus.ccrm.workflow.mapper.WorkflowMarketMapper;
import com.miplus.ccrm.workflow.model.dto.market.*;
import com.miplus.ccrm.workflow.model.enums.WorkflowStatusEnum;
import com.miplus.ccrm.workflow.model.po.Workflow;
import com.miplus.ccrm.workflow.model.po.WorkflowMarket;
import com.miplus.ccrm.workflow.model.po.WorkflowVersion;
import com.miplus.ccrm.workflow.model.vo.MarketWorkflowVO;
import com.miplus.ccrm.workflow.service.WorkflowMarketService;
import com.miplus.ccrm.workflow.service.WorkflowService;
import com.miplus.ccrm.workflow.service.WorkflowVersionService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.xml.ws.RequestWrapper;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author feixiang
* @description 针对表【workflow_market(话术市场表)】的数据库操作Service实现
* @createDate 2025-11-01 17:41:37
*/
@Service
@RequiredArgsConstructor
public class WorkflowMarketServiceImpl extends MPJBaseServiceImpl<WorkflowMarketMapper, WorkflowMarket>
    implements WorkflowMarketService {


    @Resource
    private WorkflowService workflowService;

    @Resource
    private WorkflowVersionService workflowVersionService;


    @Override
    @Transactional
    public CmdResVo manageMarketWorkflow(ShelfToMarketDTO dto, String userId) {
        if (dto == null) {
            throw new ServiceException(EnumRCode.ArgFormatErr.value, EnumRCode.ArgFormatErr.name);
        }
        Integer shelfStatus = dto.getShelfStatus();
        switch (shelfStatus) {
            case 1:
                Workflow workflow = workflowService.getById(dto.getWorkflowId());
                if (workflow == null) {
                    throw new ServiceException(EnumRCode.DataNotExist.value, EnumRCode.DataNotExist.name);
                }
                // 检查是否已经上架
                WorkflowMarket one = this.lambdaQuery()
                        .eq(WorkflowMarket::getWorkflowId, dto.getWorkflowId())
                        .eq(WorkflowMarket::getShelvedVersion, dto.getVersion())
                        .one();
                if (one != null) {
                    // 已上架
                    throw new ServiceException(50001, "该话术对应版本已上架");
                }
                WorkflowMarket market = new WorkflowMarket();
                BeanUtils.copyProperties(dto, market);
                market.setShelvedVersion(dto.getVersion());
                market.setMarketName("公共市场");
                market.setCreatedBy(userId);
                boolean success = save(market);
                if (!success) {
                    throw new ServiceException(EnumRCode.RuntimeException.value, EnumRCode.RuntimeException.name);
                }
                //版本表设置状态为上架
                //获取版本存储的信息，根据话术id和版本id
                WorkflowVersion workflowVersion = workflowVersionService.getOne(new MPJLambdaWrapper<WorkflowVersion>()
                        .eq(WorkflowVersion::getWorkflowId, dto.getWorkflowId())
                        .eq(WorkflowVersion::getVersion, dto.getVersion()));
                if (workflowVersion == null) {
                    throw new ServiceException(50001, "该话术对应版本不存在");
                }
                workflowVersion.setIsShelved(WorkflowStatusEnum.SHELVED.getCode());
                boolean success1 = workflowVersionService.updateById(workflowVersion);
                if (!success1) {
                    throw new ServiceException(EnumRCode.RuntimeException.value, EnumRCode.RuntimeException.name);
                }
                return new CmdResVo(1, market.getId());

            case 0:
                //检测话术是否存在在市场,话术是否存在。
                WorkflowMarket exist = this.lambdaQuery()
                        .eq(WorkflowMarket::getWorkflowId, dto.getWorkflowId())
                        .eq(WorkflowMarket::getShelvedVersion, dto.getVersion())
                        .one();
                if (exist == null) {
                    throw new ServiceException(50001, "该话术对应版本未上架市场");
                }
                boolean removed = this.removeById(exist.getId());
                if (!removed) {
                    throw new ServiceException(EnumRCode.RuntimeException.value, EnumRCode.RuntimeException.name);
                }
                //版本表设置状态为下架
                //获取版本存储的信息，根据话术id和版本id
                WorkflowVersion version = workflowVersionService.getOne(new MPJLambdaWrapper<WorkflowVersion>()
                        .eq(WorkflowVersion::getWorkflowId, dto.getWorkflowId())
                        .eq(WorkflowVersion::getVersion, dto.getVersion()));
                if (version == null) {
                    throw new ServiceException(50001, "该话术对应版本不存在");
                }
                version.setIsShelved(WorkflowStatusEnum.NOT_SHELVED.getCode());
                boolean updated = workflowVersionService.updateById(version);
                if (!updated) {
                    throw new ServiceException(EnumRCode.RuntimeException.value, EnumRCode.RuntimeException.name);
                }
                return new CmdResVo(1, exist.getWorkflowId());

            default:
                throw new ServiceException(50001, "无效的操作类型");
        }
    }

    @Override
    public IPage<MarketWorkflowVO> getMarketPage(MarketQueryDTO dto) {
        //查询话术市场表存在哪些话术id，以及版本号，版本名称。
        Page<MarketWorkflowVO> marketWorkflowVOPage = selectJoinListPage(
                new Page<>(dto.getPageNum(), dto.getPageSize()),
                MarketWorkflowVO.class,
                new MPJLambdaWrapper<WorkflowMarket>()
                        .leftJoin(Workflow.class, Workflow::getId, WorkflowMarket::getWorkflowId)
                        .leftJoin(WorkflowVersion.class, (wrapper) -> wrapper
                                .eq(WorkflowVersion::getWorkflowId, WorkflowMarket::getWorkflowId)
                                .eq(WorkflowVersion::getVersion, WorkflowMarket::getShelvedVersion))
                        .selectAll(WorkflowMarket.class)
                        .selectAs(Workflow::getName, "workflowName")
                        .selectAs(Workflow::getDescription, "description")
                        .selectAs(Workflow::getIndustryType, "industryType")
                        .selectAs(WorkflowVersion::getVersionName, "versionName")
                        .selectAs(WorkflowVersion::getVersionDesc, "versionDescription")
                        .like(JPubUtils.IsNotEmpty(dto.getKeyword()), WorkflowMarket::getMarketName, dto.getKeyword())
                        .orderByDesc(WorkflowMarket::getCreatedTime)
        );
        return marketWorkflowVOPage;

    }


    /**
     * 获取市场上一个话术所上架的所有版本号集合
     *
     * @param workflowId
     * @return
     */
    private List<Integer> getShelvedVersions(String workflowId) {
        return this.lambdaQuery()
                .select(WorkflowMarket::getShelvedVersion)
                .eq(WorkflowMarket::getWorkflowId, workflowId)
                .list()
                .stream()
                .map(WorkflowMarket::getShelvedVersion)
                .collect(Collectors.toList());
    }
}